const AJAX = getApp().ajax,
      $wx = getApp().$wx,
      getColor = getApp().globalData.getColor;

Page({
  data: {
    getColor: getColor(),
    addressInfo: {}
  },

  onLoad(options){
    $wx.setNavColor(getColor().val);

    this.setData({
      addressId: options.address_id
    });    
    this.getAddressDetails(options.address_id);
  },

  onShareAppMessage(){

  },

  // 获取手机号
  blurGetPhone(e) {
    let phone = e.detail.value;

    if (phone.length > 0 && !$wx.checkPhone(phone)) {
      $wx.showToast('请输入正确的手机号');
    }
  },

  //选择地址
  getAddress(){
    let _this = this, td = _this.data;
    wx.chooseLocation({
      success: res=>{
        td.addressDetails.address = res.name;
        td.addressDetails.address_detail = res.address;
        td.addressDetails.lat = res.latitude;
        td.addressDetails.lon = res.longitude;

        _this.setData({
          addressDetails: td.addressDetails
        });
      }
    })
  },

  // 设置默认地址
  setDefaultAddress(){
    let td = this.data;
    if (td.addressDetails){

      td.addressDetails.is_default == 1 ? 
      td.addressDetails.is_default = 2 : 
      td.addressDetails.is_default = 1;
      
      this.setData({
        addressDetails: td.addressDetails
      });
    }
  },

  //添加收货地址
  formSubmit(e){
    let form_obj = e.detail.value, td = this.data;

    if(!form_obj.name){
      $wx.showToast('请输入姓名');
    } else if (!form_obj.gender){
      $wx.showToast('请选择性别');
    } else if (!form_obj.phone){
      $wx.showToast('请输入手机号');
    } else if (form_obj.phone.length > 0 && !$wx.checkPhone(form_obj.phone)) {
      $wx.showToast('请输入正确的手机号');
    } else if (!td.addressDetails.name){
      $wx.showToast('请选择收货地址');
    } else if (!form_obj.door) {
      $wx.showToast('请输入门牌号');
    }else{


      wx.showLoading({
        title: '编辑中...',
        mask: true
      });
      
      AJAX.updateAddress({
        name: form_obj.name,
        mobile: form_obj.phone,
        is_default: form_obj.default || '2',
        address: td.addressDetails.address,
        address_detail: td.addressDetails.address_detail,        
        sex: form_obj.gender,
        lat: td.addressDetails.lat,
        lon: td.addressDetails.lon,
        id: td.addressId,
        door: form_obj.door
      },(status, data, msg)=>{
        wx.hideLoading();
        if(status){
          wx.navigateBack();
        }else{
          $wx.showToast(msg);
        }
      });
    }
  },

  /*获取地址详情*/ 
  getAddressDetails(id){
    let _this = this;
    wx.showNavigationBarLoading();

    AJAX.addressDetails({id},(status, data, msg)=>{
      wx.hideNavigationBarLoading();
      if(status){
        _this.setData({
          addressDetails: data
        });
      }else{
        $wx.showToast(msg);
      }
    });
  }
});